<?php

namespace app\chat\controller;

//加载redis驱动
use redis\redis;
//加载model
use app\chat\model\LoginModel;
use GatewayClient\Gateway;
use Workerman\Worker;

class Index extends CommonController {

    public $login_model;
    public $redis;

    function __construct() {
        parent::__construct();
//        $this->login_model = new LoginModel();
//        $this->redis = new redis();
    }

    function yali() {
        $worker = new Worker('tcp://0.0.0.0:1234');
// 进程数配置成cpu核数-1，保留一个cpu给ab进程
        $worker->count = 3;
        $worker->onMessage = function($connection, $data) {
            $connection->send("HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nServer: workerman\1.1.4\r\n\r\nhello");
        };
        Worker::runAll();
    }

    //直接给所有在线用户发送信息
    function send() {
        Gateway::$registerAddress = '127.0.0.1:1236';
        $data['type'] = 'lgon';
        $data['asdad'] = 'adadadads';
        $rs = Gateway::sendToAll(json_encode($data));
        var_dump($rs);
    }

    /**
     * 登录
     * @return type
     */
    public function index() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $user_info = $this->login_model->check_user(trim($data['name']), trim($data['pwd']));
            if ($user_info['status'] == 'error') {
                $this->error('登录失败,请重试');
            }
            //设置cookie
            $uid_key = md5($user_info['data']['id']);
            $encode_token = pbulic_encode($uid_key);
            //redis 保存

            $this->redis->redis_set($uid_key, $encode_token, 7200);
        } else {
            return $this->fetch('index');
        }
    }

    function back() {
        $this->login_model->backups();
        $this->success('备份成功');
    }

}
